package com.stream.utils.interceptor;

import com.stream.model.entity.TokenEntity;
import com.stream.service.TokenService;
import com.stream.utils.RRException;
import com.stream.utils.annotation.IgnoreAuth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限验证
 * Created by yebaokang on 2017/5/22.
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter{
    @Autowired
    private TokenService tokenService;

    public static final String LOGIN_USER_KEY = "login_user_key";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        IgnoreAuth ignoreAuth = null;
        if (handler instanceof HandlerMethod) {
            ignoreAuth = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        }else{
            return true;
        }

        //如果没有配置 @IgnoreAuth 注解，则不验证 token
        if (ignoreAuth != null) {
            return true;
        }

        //从 header 中获取 token
        String token = request.getHeader("token");
        //如果header没找到，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token ");
        }

        //根据token，查询 token信息
        TokenEntity tokenEntity = tokenService.queryByToken(token);
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new RRException("token失效，请重新登录");
        }

        // 设置userId到request里，后续跟进 userId,获取用户信息
        request.setAttribute(LOGIN_USER_KEY, tokenEntity.getUserId());
        return true;
    }
}
